package com.example.edu_oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.edu_oss.service.OssService;
import com.example.edu_oss.utils.ConstantUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {

        String endpoint= ConstantUtils.END_POINT;
        String keyid= ConstantUtils.KEY_ID;
        String keysecret= ConstantUtils.KEY_SECRET;
        String bucketname= ConstantUtils.BUCKET_NAME;

        try {
            OSS oss = new OSSClientBuilder().build(endpoint, keyid, keysecret);

            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();

            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename=uuid+filename;

            String date = new DateTime().toString("yyyy/MM/dd");
            filename=date+"/"+filename;
            oss.putObject(bucketname,filename,inputStream);
            oss.shutdown();

            String url="https://"+bucketname+"."+endpoint+"/"+filename;
            return url;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
